package com.example.client.config;

import org.springframework.boot.actuate.health.Health;
import org.springframework.boot.actuate.health.HealthIndicator;
import org.springframework.stereotype.Component;

import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

/**
 * 监控接口的健康情况
 *
 */
@Component
public class ApiHealthIndicator implements HealthIndicator {

    @Override
    public Health health() {
        Map<String, String> detailMap = new HashMap<>();
        String hisApiUrl = "http://192.168.1.107:8081/client";
        int hisApiCode = testUrlConnection(hisApiUrl); // perform some specific health check
        if (hisApiCode != 200) {
            detailMap.put("baidu Api", "无法访问  " + hisApiUrl);
        }
        if (detailMap.size() > 0) {
            return Health.down().withDetails(detailMap).build();
        }
        return Health.up().withDetail("baidu Api","200").build();
    }

    public int testUrlConnection(String address) {
        int status = 404;
        try {
            URL urlObj = new URL(address);
            HttpURLConnection oc = (HttpURLConnection) urlObj.openConnection();
            oc.setUseCaches(false);
            oc.setConnectTimeout(3000); // 设置超时时间
            status = oc.getResponseCode();// 请求状态
            if (200 == status) {
                // 200是请求地址顺利连通。。
                return status;
            }
        } catch (Exception e) {
            //e.printStackTrace();
            return status;
        }
        return status;
    }
}